package pro.cherish.knowledgemqrabbitmq.t1;

import com.rabbitmq.client.*;
import pro.cherish.knowledgemqrabbitmq.util.RabbitUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author 创建人：cherish
 * @version 版本号：V1.0
 * <p>
 * ***************************修订记录************************************
 * 2019-10-27 cherish 创建该类功能。
 * **********************************************************************
 * </p>
 * @ClassName 类名：MsgConsumer
 * @Description 功能说明：
 * <p>
 * TODO
 * </p>
 * **********************************************************************
 * @date 创建日期： 2019-10-27 cherish
 */
public class MsgConsumer {

    public static void consumerMsg(String exchange, String queue, String routingKey) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = RabbitUtil.getConnectionFactory();
        //建立连接
        Connection connection = connectionFactory.newConnection();
        //建立通道
        Channel channel = connection.createChannel();
        //消息队列
        channel.queueDeclare(queue, true, false, false, null);
        //    绑定队列到交换机
        channel.queueBind(queue, exchange, routingKey);
        System.out.println(queue + "[*] Waiting for message. To exist press CTRL+C");
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                try {
                    System.out.println(queue + " [x] Received '" + message);
                } finally {
                    System.out.println(queue + " [x] Done");
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }
            }
        };
        // 取消自动ack
        channel.basicConsume(queue, false, consumer);
    }
}
